###########################################################################
#	$Id: bLib.p 4 2007-03-17 06:47:01Z beave $
###########################################################################

@CLASS
bLib


@auto[]
$PLATFORM[]

$PARSER_VERSION[^Lib:getParserVersion[]]

^if(^PARSER_VERSION.comment.match[win][gi]){
	$PLATFORM[win]
}
#end @auto[]



@refresh[strParams][sParams]
^if(def $strParams){
	$sParams[^if(^request:uri.pos[?]>=0){&}{?}^strParams.trim[]]
}

^Lib:location[http://^taint[as-is][${env:SERVER_NAME}:${env:SERVER_PORT}$request:uri]^untaint[uri]{$sParams}]
#end @refresh[]



###########################################################################
#	Options:
#		$.full_path(bool) = false
#		$.platform[string] = $PLATFORM
#	Result: string
###########################################################################
@preparePath[strPath;hshParams][hParams]
^if(!def $strPath){
	^throw[blib.spec;^$strPath;param not specified]
}

$hParams[^hash::create[$hshParams]]

$result[^file:fullpath[$strPath]]

^if($hParams.full_path){
	$result[${request:document-root}$result]
}

# parsing slashes
^switch[^if(def $hParams.platform){$hParams.platform}{$PLATFORM}]{
	^case[win]{
		$result[^result.replace[^table::create{from	to^#0A/	\}]]
	}
	^case[unix]{
		$result[^result.replace[^table::create{from	to^#0A\	/}]]
	}
}
#end @preparePath[]



@processFile[altParams][sFile;hParams;sMain;fFile;sFileBody]
^if(!def $altParams){
	^throw[bLib.spec;^$altParams;param not specified]
}

^if($altParams is 'hash'){
	$hParams[^hash::create[$altParams]]

	^if(!def $hParams.file){
		^throw[bLib.spec;^$.file;option not specified]
	}
	$sFile[$hParams.file]

	^if(def $hParams.main){
		$sMain[$hParams.main]
	}
}{
	$sFile[$Params]
}

# loading file
$fFile[^file::load[text;$sFile]]

$sFileBody[^taint[as-is][^fFile.text.trim[]]]

^try{

	^process[$caller.self]{$sFileBody}[
		^if(def $sMain){
			$.main[$sMain]
		}
		$.file[$sFile]
	]

}{

	$exception.handled(1)

	^if(def $sMain){
#		if 'main' option specified, trying change main method
		^if(^sFileBody.pos[@main^[^]] >= 0){
#			if @main[] founded, replacing
			$sFileBody[^sFileBody.match[\@main\^[\^]][g]{@${sMain}^[^]}]
		}{
			^if(def $sFileBody){
#				if @main[] not founded, create
				$sFileBody[@${sMain}^[^]	^#0A$sFileBody]
			}
		}
	}

	^process[$caller.self]{$sFileBody}

}
#end @processFile[]
